import { PlusOutlined } from "@ant-design/icons";
import { BetaSchemaForm } from "@ant-design/pro-components";
import { PageContainer } from "@ant-design/pro-layout"
import ProTable, { ActionType } from "@ant-design/pro-table";
import type { CrudFilters } from "@refinedev/core";
import { SysAttachment } from "@sker/model";
import { useModel, useModal, useForm, toWebUrl } from "@sker/sdk";
import { renderAdminPage, useServerData, AttachmentCategorySelector, SkerUploadOne, AttachmentPreview } from "@sker/ui"
import { Button, Card, Image, Modal, Popconfirm } from "antd";
import { useEffect, useRef, useState } from "react";

export const AttachmentPage: React.FC<{}> = ({ }) => {
    const [serverData] = useServerData();
    const model = useModel(SysAttachment)
    const uploadUrl = toWebUrl('imeepos/core/attachment')
    const { props: modalProps, setOpen, setTitle } = useModal('添加附件', () => setRecord(null))
    const [record, setRecord] = useState<any>()
    const [pres, setPres] = useState<string[]>()
    const actionRef = useRef<ActionType>()
    const { props: formProps, form } = useForm([
        { dataIndex: 'name', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'url', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'id', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'bucket', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'from', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'hash', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'type', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'tags', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        {
            title: '附件',
            renderFormItem(schema, config, form, action) {
                const id = form.getFieldValue('id')
                const name = form.getFieldValue('name')
                const url = form.getFieldValue('url')
                const fileList: any[] = [];
                if (id) {
                    fileList.push({
                        uid: id,
                        url: url,
                        name: name,
                    })
                }
                return <SkerUploadOne value={fileList} action={uploadUrl} onUpload={(values) => {
                    form.setFieldsValue({ ...values })
                }} />
            },
        },
    ], async (values) => {
        if (record) {
            values.id = record.id;
        }
        if (pres && pres.length > 0) {
            values.type = pres[0]
        }
        values.tags = values.tags.join(',')
        await model.save(values, ['id'])
        setOpen(false)
        actionRef.current?.reload();
        setRecord(null)
    })
    useEffect(() => {
        if (!record) {
            form.resetFields()
        }
        form.setFieldsValue(record)
    }, [record])
    return <PageContainer title={serverData?.title || '附件管理'}>
        <div className="flex">
            <div className="w-400px">
                <AttachmentCategorySelector onSelect={(keys: string[]) => {
                    if (keys.length > 0) {
                        form.setFieldValue('type', keys[0])
                    }
                    setPres(keys)
                }} />
            </div>
            <div className="flex-1 ml-24px">
                <Modal {...modalProps}>
                    <BetaSchemaForm {...formProps} />
                </Modal>
                <Card title={'附件列表'} extra={
                    <>
                        <Button icon={<PlusOutlined />} type={'primary'} size="small" onClick={() => {
                            setRecord(null)
                            setOpen(true)
                        }}></Button>
                    </>
                }>
                    <ProTable
                        search={false}
                        toolBarRender={false}
                        actionRef={actionRef}
                        rowKey={record => record.id}
                        columns={[
                            { title: '名称', dataIndex: 'name' },
                            {
                                title: '资源', dataIndex: 'url', render(dom, entity, index, action, schema) {
                                    return <AttachmentPreview className={'w-60px h-60px'} value={[entity.hash]} />
                                },
                            },
                            {
                                title: '操作',
                                align: 'right',
                                render(dom, entity, index, action, schema) {
                                    return <>
                                        <Button size={'small'} type={'link'} onClick={e => {
                                            setTitle('编辑附件')
                                            setOpen(true)
                                            setRecord(entity)
                                        }}>编辑</Button>
                                        <Popconfirm onConfirm={async e => {
                                            await model.delete(entity.id)
                                            await actionRef.current?.reload();
                                        }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                                            <Button size={'small'} type={'link'} danger >删除</Button>
                                        </Popconfirm>
                                    </>
                                },
                            }
                        ]}
                        params={{
                            pres
                        }}
                        request={async (params) => {
                            const filters: CrudFilters = [];
                            if (params.pres && params.pres.length > 0) {
                                filters.push({ field: 'type', operator: 'in', value: params.pres })
                            }
                            return model.find(['id', 'url', 'name', 'type','hash'], [
                                ...filters
                            ], [{ field: 'create_date', order: 'desc' }], {
                                current: params.current,
                                pageSize: params.pageSize
                            })
                        }}
                    />
                </Card>
            </div>
        </div>
    </PageContainer>
}

renderAdminPage(AttachmentPage, 'imeepos/core/web/attachment')